package com.sj.parksdk.utils;

import com.sj.parksdk.net.manager.TokenManager;
import com.sj.parksdk.net.result.databean.Data_Token;
import com.sj.parksdk.setting.CommonKey;
import com.tencent.mmkv.MMKV;
import com.xuexiang.xhttp2.logs.HttpLog;
import com.xuexiang.xutil.common.StringUtils;

public class TokenUtils {

    private TokenUtils() {
        throw new UnsupportedOperationException("u can't instantiate me...");
    }

    public static void clearToken() {
        MMKVUtils.put(CommonKey.TOKEN_IS_LOGIN, false);
        MMKVUtils.remove(CommonKey.TOKEN_ACCESS_TOKEN);
        MMKVUtils.remove(CommonKey.TOKEN_REFRESH_TOKEN);
        MMKVUtils.remove(CommonKey.TOKEN_EXPRESS_ON);
        TokenManager.newInstance();
    }

    public static boolean hasToken() {
        return MMKV.defaultMMKV().containsKey(CommonKey.TOKEN_ACCESS_TOKEN);
    }

    /**
     * 处理登录成功的事件
     *
     * @param data Token信息
     */
    public static boolean handleLoginSuccess(Data_Token data) {
        if (data == null) return false;
        if (StringUtils.isEmpty(data.getAccess_token())
                || StringUtils.isEmpty(data.getRefresh_token())
                || StringUtils.isEmpty(data.getToken_type())) return false;
        TokenManager.getInstance().setToken(data.getAccess_token());
        TokenManager.getInstance().setSign(data.getToken_type());
        TokenManager.getInstance().setTokenExpiresOn(data.getExpires_on());
        TokenManager.getInstance().setRefreshToken(data.getRefresh_token());
        TokenManager.getInstance().refreshLoginState(true);
        MMKVUtils.put(CommonKey.TOKEN_IS_LOGIN, true);
        MMKVUtils.put(CommonKey.TOKEN_ACCESS_TOKEN, data.getAccess_token());
        MMKVUtils.put(CommonKey.TOKEN_REFRESH_TOKEN, data.getRefresh_token());
        MMKVUtils.put(CommonKey.TOKEN_EXPRESS_ON, data.getExpires_on());
        HttpLog.e("密码登录token：" + data.getAccess_token());
        return true;
//        if (!StringUtils.isEmpty(token)) {
//            XToastUtils.success("登录成功！");
////            MobclickAgent.onProfileSignIn("github", token);
//            setToken(token);
//            return true;
//        } else {
//            XToastUtils.error("登录失败！");
//            return false;
//        }
    }

    /**
     * 处理登出的事件
     */
    public static void handleLogoutSuccess() {
//        MobclickAgent.onProfileSignOff();
        //登出时，清除账号信息
        clearToken();
        XToastUtils.success("登出成功！");
        //跳转到登录页
//        ActivityUtils.startActivity(LoginActivity.class);
    }

}
